import React, { ForwardedRef, RefObject, useEffect, useRef, useState } from 'react';
import './popper.scss';
import ReactDOM from 'react-dom';
import { getDOMPosition, getDOMSize } from '../../utils';

export interface PopperProps {
	children?: React.ReactNode;
	className?: string;
	open?: boolean;
	appendToBody?: boolean;
	ref?: ForwardedRef<HTMLDivElement>;
	wrapperRef?: RefObject<HTMLDivElement>;
}

const DefaultPopper = (props: PopperProps) => {
	const { children = '', className = '', wrapperRef = null } = props;
	const popperRef = useRef<HTMLDivElement>(null);

	let options = {
		root: document.body,
		rootMargin: '0px',
		threshold: 1.0,
	};
	const callback = (entries: IntersectionObserverEntry[]) => {
		entries.forEach((entry) => {
			console.log('entry', entry);
		});
	};
	let observer = new IntersectionObserver(callback, options);
	observer.observe(wrapperRef?.current as HTMLElement);

	const [wrapperX, setWrapperX] = useState<number>(0)
	const [wrapperY, setWrapperY] = useState<number>(0)
	const handlePopper = () => {
		const { width: wrapperWidth, height: wrapperHeight } = getDOMSize(wrapperRef?.current);
		const { x, y } = getDOMPosition(wrapperRef?.current);
		setWrapperX(x);
		setWrapperY(y);
		console.log('wrapperX', wrapperX, 'wrapperY', wrapperY);
		if (popperRef.current) {
			popperRef.current.style.inset = `${wrapperHeight + y}px 0 0 ${x}px `;
			popperRef.current.style.width = `${wrapperWidth}px`;
		}  
	};
	useEffect(() => {
		console.log('wrapperRef', wrapperRef);
		handlePopper();
	}, [wrapperRef?.current?.getBoundingClientRect()]);

	useEffect(() => {
		console.log('wrapperX');
	}, [wrapperX, wrapperY])

	return (
		<div
			ref={popperRef}
			className={`hs-ui-popper ${className}`}>
			<div className="hs-ui-popper__wrapper">
				<div className="hs-ui-popper__content">{children}</div>
			</div>
		</div>
	);
};

const Popper = (props: PopperProps) => {
	const { open, appendToBody = true } = props;
	const [newPopper, setNewPopper] = useState<Element | null>(null);

	useEffect(() => {
		if (open) {
			const div = document.createElement('div');
			document.body.appendChild(div);
			setNewPopper(div);
		} else {
			if (newPopper) {
				document.body.removeChild(newPopper);
				setNewPopper(null);
			}
		}
	}, [open]);

	return appendToBody
		? newPopper && ReactDOM.createPortal(<DefaultPopper {...props} />, newPopper)
		: open && <DefaultPopper {...props} />;
};

export default Popper;
